﻿using UnityEngine;
using System.Collections;

public class MachineGun : MonoBehaviour 
{
	public GameObject m_barrel;
    public GameObject m_prefabBullet;
    public GameObject m_bulletPre;
	public int m_shootRate;

    protected bool m_isShoot;
    protected Vector2 m_shootDir;
    protected float m_shootCooldown;
    protected float m_timer;
    protected Vector2 m_dir;

	// Use this for initialization
	void Start () 
	{
        m_isShoot = false;
        m_timer = 0;
	}
	
	// Update is called once per frame
	void Update () 
	{
        if (m_isShoot)
        {
            m_timer += Time.fixedDeltaTime;

            if (m_timer >= m_shootCooldown)
            {
                m_timer -= m_shootCooldown;

                fire();
            }
        }
	}

    /// <summary>
    /// shoot 
    /// </summary>
    /// <param name="rate"></param>
    public void Shoot()
    {
        m_isShoot = true;

        m_shootCooldown = 60.0f / (float)m_shootRate;
    }

    /// <summary>
    /// aim to 
    /// </summary>
    /// <param name="dir"></param>
    public void AimTo(Vector2 dir)
    {
        m_shootDir = dir;

        rotateGun(m_shootDir);
    }

    /// <summary>
    /// stop shoot 
    /// </summary>
    public void StopShoot()
    {
        m_isShoot = false;
    }


    //---------------------------- private functions ----------------------------


    /// <summary>
    /// fire a bullet 
    /// </summary>
    protected void fire()
    {
        GameObject go = (GameObject)Instantiate(m_prefabBullet);
        go.transform.position = m_bulletPre.transform.position;

        Bullet bullet = go.GetComponent<Bullet>();
        bullet.SetDir(m_dir);
    }


    /// <summary>
    /// rotate gun 
    /// </summary>
    /// <param name="dir"></param>
    protected void rotateGun(Vector2 dir)
    {
        m_dir = dir;

        float angle = Vector2.Angle(Vector2.up, dir);
        if (dir.x > 0)
        {
            angle = -angle;
        }

		m_barrel.transform.localRotation = Quaternion.Euler(0, 0, angle);
    }


}
